package com.yanwq.sayhi.controller.user.activity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

import com.alibaba.fastjson.JSONObject;
import com.yanwq.sayhi.R;
import com.yanwq.sayhi.base.BaseToolbarActivity;
import com.yanwq.sayhi.common.client.OkJsonObjectResponseCallback;
import com.yanwq.sayhi.common.client.OkRestClient;
import com.yanwq.sayhi.common.constant.RegexConstant;
import com.yanwq.sayhi.controller.user.UserMgr;
import com.yanwq.sayhi.dao.bean.User;
import com.yanwq.sayhi.widget.MToast;

import java.util.regex.Pattern;

import butterknife.BindView;

public class MottoActivity extends BaseToolbarActivity {
    @BindView(R.id.motto_motto)
    EditText mMottoV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_motto);
    }

    @Override
    public void init() {

    }

    @Override
    public void initView() {
        mToolbar.setTitle("修改签名");
        mMottoV.setText(UserMgr.get().getMotto());
        mMottoV.setSelection(UserMgr.get().getMotto().length());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_send, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        send();
        return true;
    }

    private void send() {
        if (!Pattern.matches(RegexConstant.motto, mMottoV.getText().toString())) {
            MToast.showShort(MottoActivity.this, "屌丝你还没写签名");
            return;
        }

        updateMotto();
    }

    private void updateMotto() {
        User user = UserMgr.get();
        user.setMotto(mMottoV.getText().toString());

        OkRestClient.getInstance().post(MottoActivity.this,
                "/user/update",
                user,
                new OkJsonObjectResponseCallback() {
                    @Override
                    public void onStart() {
                        showProgressDialog("正在修改签名");
                    }

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        UserMgr.update(jsonObject);
                        MToast.showShort(MottoActivity.this, "恭喜，新签名很嗨");
                        finish();
                    }

                    @Override
                    public void onStop() {
                        cancelProgressDialog();
                    }
                });
    }
}
